package com.xq.flutter_auto_track;

import android.content.Context;
import android.provider.Settings;
import android.telephony.TelephonyManager;

import androidx.annotation.NonNull;

import io.flutter.embedding.engine.plugins.FlutterPlugin;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.MethodChannel.MethodCallHandler;
import io.flutter.plugin.common.MethodChannel.Result;

import com.bun.miitmdid.core.MdidSdkHelper;

import java.util.Map;

/** FlutterAutoTrackPlugin */
public class FlutterAutoTrackPlugin implements FlutterPlugin, MethodCallHandler {
  /// The MethodChannel that will the communication between Flutter and native Android
  ///
  /// This local reference serves to register the plugin with the Flutter Engine and unregister it
  /// when the Flutter Engine is detached from the Activity
  private MethodChannel channel;
  private Context mContext;

  @Override
  public void onAttachedToEngine(@NonNull FlutterPluginBinding flutterPluginBinding) {
    channel = new MethodChannel(flutterPluginBinding.getBinaryMessenger(), "com.xq.auto.track.channel");
    channel.setMethodCallHandler(this);
    mContext = flutterPluginBinding.getApplicationContext();
  }

  @Override
  public void onMethodCall(@NonNull MethodCall call, @NonNull Result result) {
    if (call.method.equals("getPlatformVersion")) {
      result.success("Android" + android.os.Build.VERSION.RELEASE);
    } else if (call.method.equals("auto_track_setup")) {
      AutoTrackManager.setup((Map) call.arguments, result, mContext);
    } else if (call.method.equals("auto_track_event")) {
      AutoTrackManager.event((Map) call.arguments, result);
    } else if (call.method.equals("request_android_id")) {
      String androidId = Settings.Secure.getString(mContext.getContentResolver(), Settings.Secure.ANDROID_ID);
      result.success(androidId);
    } else if (call.method.equals("request_android_OAID")) {
      MdidSdkHelper.InitSdk(mContext, true, (b, idSupplier) -> {
        if (idSupplier != null) {
          String md_oaid = idSupplier.getOAID();
          result.success(md_oaid);
        }
      });
    } else if (call.method.equals("request_android_imei")) {
      String imei = ((TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE)).getDeviceId();
      result.success(imei);
    } else if (call.method.equals("query_device_bd_did")) {
      AutoTrackManager.getTrackInfo(result, mContext);
    } else {
      result.notImplemented();
    }
  }

  @Override
  public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) {
    channel.setMethodCallHandler(null);
  }


}
